package com.erp.ae.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.erp.ae.domain.enums.AliExpressInterfaceEnum;
import com.erp.ae.service.IAePromotionActivityService;
import com.erp.ae.utils.AeApiUtils;
import com.global.iop.domain.Protocol;
import com.ruoyi.common.core.domain.R;
import com.erp.ae.utils.AeApiUtils;
import com.ruoyi.common.core.utils.oldUtils.StringUtils;
import com.ruoyi.shop.api.RemoteSellerStoreActivityService;
import com.ruoyi.shop.api.RemoteSellerStoreService;
import com.ruoyi.shop.api.domain.ErpSellerStoreEmpower;
import com.ruoyi.shop.api.domain.ErpSellerStorePromotionActivity;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * 商户订单Service业务层处理
 *
 * @author erp
 * @date 2023-03-09
 */
@RequiredArgsConstructor
@Service
public class AePromotionActivityServiceImpl implements IAePromotionActivityService {
    @Resource
    RemoteSellerStoreService remoteSellerStoreService;
    @Resource
    RemoteSellerStoreActivityService remoteSellerStoreActivityService;

    @Override
    public R<Object> editActivityToAe(Map discInputDto, String storeId) {
        String accessToken = AeApiUtils.getToken(storeId);
        if (accessToken == null) {
            R.fail("店铺未授权");
        }
        String msg =
                AeApiUtils.sendRequest(
                        AliExpressInterfaceEnum.findOrderReceiptInfo.getCode(),
                        "param_limited_disc_input_dto",
                        discInputDto,
                        Protocol.TOP,
                        accessToken
                );
        if (msg != null && !msg.contains("error_response")) {
            System.out.println(msg);
            return R.ok(msg);
        } else {
            return R.fail("修改失败");
        }
    }

    @Override
    public R<Object> createActivityToAe(Map discInputDto, String storeId) {
        String accessToken = AeApiUtils.getToken(storeId);
        if (accessToken == null) {
            R.fail("店铺未授权");
        }
        String msg =
                AeApiUtils.sendRequest(
                        AliExpressInterfaceEnum.createPromotionActivity.getCode(),
                        "param_limited_disc_input_dto",
                        discInputDto,
                        Protocol.TOP,
                        accessToken
                );
        if (msg != null) {
            System.out.println(msg);
            return R.ok(msg);
        } else {
            return R.fail("创建失败");
        }
    }

    @Override
    public R<Object> getActivityByProduct(String storeId, Map<String, Object> msgMap) {
        //生成参数Map
        //获取店铺的accessToken
        String accessToken = AeApiUtils.getToken(storeId);
        if (StringUtils.isEmpty(accessToken)) {
            return R.fail("店铺未授权");
        }
        String msg =
                AeApiUtils.sendRequest(
                        AliExpressInterfaceEnum.queryByProduct.getCode(),
                        msgMap,
                        Protocol.TOP,
                        accessToken
                );
        System.out.println(msg);
        if (msg != null && msg.contains("aliexpress_marketing_storepromotions_querybyproduct_response")) {
            return R.ok(msg);
        } else {
            return R.fail("获取营销活动失败");
        }
    }

    @Override
    public R<Object> selectStorePromotions(String storeId, Map<String, Object> msgMap) {
        String accessToken = AeApiUtils.getToken(storeId);
        if (StringUtils.isEmpty(accessToken)) {
            return R.fail("店铺未授权");
        }
        String msg =
                AeApiUtils.sendRequest(
                        AliExpressInterfaceEnum.getStorePromotionsList.getCode(),
                        "promotion_query_dto",
                        msgMap,
                        Protocol.TOP,
                        accessToken
                );
        System.out.println(msg);
        if (msg != null && msg.contains("aliexpress_marketing_storepromotions_list_response")) {
            return R.ok(msg);
        } else {
            return R.fail("获取营销活动失败");
        }
    }

    @Override
    public R<Object> findSellerCouponActivity(String activityId, String storeId) {
        //生成参数Map
        //获取店铺的accessToken
        String accessToken = AeApiUtils.getToken(storeId);
        if (StringUtils.isEmpty(accessToken)) {
            return R.fail("店铺未授权");
        }
        Map<String, Object> msgMap = new HashMap<>();
        msgMap.put("activity_id", activityId);
        String msg =
                AeApiUtils.sendRequest(
                        AliExpressInterfaceEnum.findSellerCouponActivity.getCode(),
                        msgMap,
                        Protocol.TOP,
                        accessToken
                );
        System.out.println(msg);
        if (msg != null && msg.contains("aliexpress_marketing_redefining_findsellercouponactivity_response")) {
            return R.ok(msg);
        } else {
            return R.fail("获取营销活动详情失败");
        }
    }

    @Override
    public R<Object> addProductToActivity(String storeId, Map<String, Object> map) {
        String accessToken = AeApiUtils.getToken(storeId);
        if (StringUtils.isEmpty(accessToken)) {
            return R.fail("店铺未授权");
        }
        System.out.println(map);
        String msg =
                AeApiUtils.sendRequest(
                        AliExpressInterfaceEnum.addPromotionProduct.getCode(),
                        "limited_disc_product_input_dto",
                        map,
                        Protocol.TOP,
                        accessToken
                );
        if (!msg.contains("error_response")) {
            return R.ok(msg);
        } else {
            return R.fail(msg);
        }
    }

    @Override
    public R<Object> updateProductInActivity(Map<String, Object> map, String storeId) {
        String accessToken = AeApiUtils.getToken(storeId);
        if (StringUtils.isEmpty(accessToken)) {
            return R.fail("店铺未授权");
        }
        System.out.println(map);
        String msg =
                AeApiUtils.sendRequest(
                        AliExpressInterfaceEnum.addPromotionProduct.getCode(),
                        "param_limited_disc_product_input_dto",
                        map,
                        Protocol.TOP,
                        accessToken
                );
        if (!msg.contains("error_response")) {
            return R.ok(msg);
        } else {
            return R.fail(msg);
        }
    }

    @Override
    public R<Object> deleteProductInActivity(Map<String, Object> map) {
        String storeId = (String) map.get("storeId");
        String accessToken = AeApiUtils.getToken(storeId);
        System.out.println(map);
        String msg =
                AeApiUtils.sendRequest(
                        AliExpressInterfaceEnum.delPromotionProduct.getCode(),
                        "param_aeop_limited_disc_product_id_d_t_o",
                        map,
                        Protocol.TOP,
                        accessToken
                );
        if (!msg.contains("error_response")) {
            return R.ok(msg);
        } else {
            return R.fail(msg);
        }
    }

    @Override
    public R<Object> selectStoreOngoingPromotions(String currentPage, String storeId) {
        R<Object> objectR = remoteSellerStoreService.getSellerStoreInfoById(Long.valueOf(storeId));
        String toJSONString = JSONObject.toJSONString(objectR.getData());
        ErpSellerStoreEmpower storeEmpower = JSONObject.parseObject(toJSONString, ErpSellerStoreEmpower.class);
        Map<String, Object> map = new HashMap<>();
        map.put("current_page", currentPage);
        map.put("page_size", "50");
        map.put("storeId", storeId);
//        单品折扣:ProductDiscount;搭配套餐:BundleDeals;拼团:GroupBuy;满件折:OrderQuantityDiscount;满立减:OrderPriceDiscount;满包邮:FreeShipping;
        String promotionTypeStr = "ProductDiscount,BundleDeals,GroupBuy,OrderQuantityDiscount,OrderPriceDiscount,FreeShipping";
        List<String> promotionTypeList = new ArrayList<String>(Arrays.asList(promotionTypeStr.split(",")));
        for (String promotionType : promotionTypeList) {
            map.put("promotion_type", promotionType);
            map.put("status", "Ongoing,NotStarted,Finished");
            R<Object> objectR1 = selectStorePromotions(storeId, map);

            String body = objectR1.getData().toString();
            JSONObject bodyJson = JSONObject.parseObject(body);
            Integer code = objectR1.getCode();
            if (code != 200) {
                continue;
            }
            String dataList = bodyJson
                    .getJSONObject("aliexpress_marketing_storepromotions_list_response")
                    .getJSONObject("data_list")
                    .getString("promotion_simple_info_dto");
            List<ErpSellerStorePromotionActivity> activityList = JSONArray.parseArray(dataList, ErpSellerStorePromotionActivity.class);
            if (activityList == null || activityList.size() == 0) {
                continue;
            }
            for (ErpSellerStorePromotionActivity activity : activityList) {
                //查询活动是否存在
                ErpSellerStorePromotionActivity activitySel = new ErpSellerStorePromotionActivity();
                activitySel = new ErpSellerStorePromotionActivity();
                activitySel.setPromotionId(activity.getPromotionId());
                R<Object> activityInfoR = remoteSellerStoreActivityService.selectActivityInfo(activitySel);
                String activityString = JSONObject.toJSONString(activityInfoR.getData());
                activitySel = JSONObject.parseObject(activityString, ErpSellerStorePromotionActivity.class);
                if (activitySel != null) {
                    activity.setActivityId(activitySel.getActivityId());
                }
                //1、新增活动入数据库
                activity.setStoreId(Long.valueOf(storeId));
                activity.setUserId(storeEmpower.getUserId());
                remoteSellerStoreActivityService.insertOrUpdate(activity);
            }
        }
        return R.ok("已更新活动列表");
    }


    @Override
    public R<Object> queryStoreOngoingPromotionsMsg(String storeUserName) {
        Map<String, Object> map = new HashMap<>();
        map.put("current_page", 1);
        map.put("page_size", "50");
//        单品折扣:ProductDiscount;搭配套餐:BundleDeals;拼团:GroupBuy;满件折:OrderQuantityDiscount;满立减:OrderPriceDiscount;满包邮:FreeShipping;
        map.put("promotion_type", "ProductDiscount");
        map.put("status", "Ongoing");
        R<Object> objectR1 = selectStorePromotions(storeUserName, map);
        String body = objectR1.getData().toString();
        JSONObject bodyJson = JSONObject.parseObject(body);
        if (body.contains("aliexpress_marketing_storepromotions_list_response")){
            String dataList = bodyJson
                    .getJSONObject("aliexpress_marketing_storepromotions_list_response")
                    .getJSONObject("data_list")
                    .getString("promotion_simple_info_dto");
            return R.ok(dataList);
        }else {
            return R.fail();
        }

    }


}
